import { saveAccount } from '@/services/api/api-admin-account';
import { treeOrganization } from '@/services/api/api-admin-organization';
import { getRolePage } from '@/services/api/api-admin-role';
import { CloseOutlined, FolderOutlined, HomeOutlined, PlusOutlined } from '@ant-design/icons';
import ProForm, { DrawerForm, ProFormText } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import { Button, Empty, message } from 'antd';
import Tree, { DataNode } from 'antd/es/tree';
import React, { useEffect, useState } from 'react';

interface AddAccountProps {
  organizationId: string | undefined;
  onRefurbish: () => void;
}
const AddAccount: React.FC<AddAccountProps> = ({ organizationId, onRefurbish }) => {
  const [selectedRoleRowKeys, setSelectedRoletRowKeysState] = useState<React.Key[]>([]);

  /**
   * 初始化树形数据
   */
  const [dataTree, setDataTreeState] = useState<DataNode[]>();
  /**
   * 树形列表选择数据
   */
  const [selectNode, setSelectNodeState] = useState<any>();
  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          title: val.name,
          key: val.id,
          item: val,
          disabled: val.isFolder === 1 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
          icon:
            val.state === 1 ? (
              val.isFolder === 0 ? (
                <HomeOutlined />
              ) : (
                <FolderOutlined />
              )
            ) : (
              <CloseOutlined />
            ),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载权限详情
   * @param key
   */
  const loadOrganizationData = async () => {
    try {
      const response = await treeOrganization();
      if (response.code === 0) {
        const treeData = new Array<DataNode>();
        treeData.push({
          title: '融媒通',
          key: '0',
          item: { id: '0', name: '融媒通' },
          children: readyTreeData(response.data),
        });
        setDataTreeState(treeData);
      }
    } catch (error) { }
  };

  /**
   * 加载权限树请求网络
   */
  useEffect(() => {
    loadOrganizationData();
  }, []);

  return (
    <DrawerForm
      key="add_account"
      title="新建用户"
      drawerProps={{
        destroyOnClose: true,
      }}
      trigger={
        <Button type="primary">
          <PlusOutlined />
          新建
        </Button>
      }
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          setSelectNodeState(undefined);
          setSelectedRoletRowKeysState([]);
        }
      }}
      onFinish={async (values) => {
        if (selectedRoleRowKeys.length === 0) {
          message.warning('请选择角色！');
          return false;
        }

        if (selectNode !== undefined) {
          if (selectNode?.node?.selected) {
            message.warning('请选择组织！');
            return false;
          }

          if (selectNode?.node?.item.isFolder === 1) {
            message.warning('所选组织为文件夹，请重新选择！');
            return false;
          }
        } else {
          message.warning('请选择组织！');
          return false;
        }

        const response = await saveAccount({
          organizationId: selectNode ? selectNode?.node?.key : organizationId,
          roleIds: selectedRoleRowKeys,
          ...values,
        });
        if (response.code === 0) {
          message.success('提交成功');
          onRefurbish();
          return true;
        } else {
          return false;
        }
      }}
    >
      <ProForm.Group>
        <ProFormText
          width="md"
          name="name"
          label="账号"
          rules={[{ required: true, message: '请输入账号' }]}
        />
        <ProFormText
          width="md"
          name="phone"
          label="电话"
          rules={[{ required: true, message: '请输入电话' }]}
        />
      </ProForm.Group>

      <ProTable<AdminRoleData.Role>
        ghost
        rowSelection={{
          selectedRowKeys: selectedRoleRowKeys,
          type: 'checkbox',
          onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
            setSelectedRoletRowKeysState(selectedRowKeys);
          },
        }}
        tableAlertRender={false}
        columns={[
          {
            title: '名称',
            key: 'name',
            dataIndex: 'name',
          },
          {
            title: '描述',
            key: 'describes',
            dataIndex: 'describes',
          },
        ]}
        request={async (params = {}) => {
          params.state = 1;
          params.deleted = 0;
          const response = await getRolePage({
            ...params,
          });
          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        rowKey="id"
        options={false}
        search={false}
        tableLayout="fixed"
        dateFormatter="string"
        headerTitle="角色列表"
        bordered
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 50,
        }}
      />

      {dataTree && dataTree.length ? (
        <Tree
          defaultExpandAll
          height={800}
          showLine={{ showLeafIcon: false }}
          showIcon={true}
          treeData={dataTree}
          defaultSelectedKeys={[organizationId]}
          onSelect={(selectedKeys: React.Key[], info: any) => {
            setSelectNodeState(info);
          }}
        />
      ) : (
        <Empty />
      )}
    </DrawerForm>
  );
};
export default AddAccount;
